package com.zhangjingcheng.yunyixia.interceptior;

import com.zhangjingcheng.yunyixia.constant.MessageConstant;
import com.zhangjingcheng.yunyixia.exception.UserBusinessException;
import com.zhangjingcheng.yunyixia.properties.JwtProperties;
import com.zhangjingcheng.yunyixia.util.JwtUtil;
import com.zhangjingcheng.yunyixia.util.RedisUtil;
import com.zhangjingcheng.yunyixia.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 解析令牌
        String authorization = request.getHeader(jwtProperties.getTokenName());
        try {
            String token = (String) redisUtil.get(authorization);
            if (token == null || token.isEmpty()) {
                // token失效
                throw new UserBusinessException(MessageConstant.USER_NOT_LOGIN);
            }
            Map<String, Object> deUserMap = jwtUtil.parseToken(authorization);
            ThreadLocalUtil.setId((Integer) deUserMap.get("id"));
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除缓存
        ThreadLocalUtil.remove();
    }
}
